import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server: {
    port: 3000,
    proxy: {
      '/api': {
        target: 'http://localhost:8000',
        changeOrigin: true,
        secure: false,
        ws: false,
        configure: (proxy, options) => {
          proxy.on('error', (err, req, res) => {
            console.log('proxy error', err);
          });
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log('Sending Request to the Target:', req.method, req.url);
            // 确保Authorization头被正确传递
            if (req.headers.authorization) {
              proxyReq.setHeader('Authorization', req.headers.authorization);
            }
          });
          proxy.on('proxyRes', (proxyRes, req, res) => {
            console.log('Received Response from the Target:', proxyRes.statusCode, req.url);
            // 处理重定向响应，确保后续请求包含认证头
            if (proxyRes.statusCode === 307 && proxyRes.headers.location) {
              console.log('Redirect detected, location:', proxyRes.headers.location);
            }
          });
        },
        // 自定义重写函数，确保重定向时保留认证头
        onProxyReq: (proxyReq, req, res) => {
          // 复制所有原始头，包括Authorization
          Object.keys(req.headers).forEach(key => {
            if (key.toLowerCase() !== 'host') { // 不复制host头
              proxyReq.setHeader(key, req.headers[key]);
            }
          });
        }
      }
    }
  }
})
